#!/usr/bin/python
#
# Copyright (C) 2008 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" This sample demonstrates how to query meta resources based on their tags. """

import time
import rawsc
import rawsc.service
from rawsc import rass
import rawsc.rass.service
from rawsc.rass import Tag, Meta
try:
  from xml.etree import cElementTree as ElementTree
except ImportError:
  try:
    import cElementTree as ElementTree
  except ImportError:
    from elementtree import ElementTree

# user credentials for authentication to RASS
USER = "XXX"
PWD = "XXX"
SERVER = "rass.cdn0XXX.rambla.be"

# path to a local file that may be uploaded
LOCAL_FILE = "/path/to/local/file.mp4"

try:
    # Create a Rass instance, passing it your login credentials and the base service uri
    client = rawsc.rass.service.RassService(username=USER, password=PWD, server=SERVER)
    
    # upload some files, so we can tag them
    eagle_entry = client.postItem(dirpath = "/tutorial9", filename = "eagle.mp4", local_path = LOCAL_FILE)
    sparrow_entry = client.postItem(dirpath = "/tutorial9", filename = "sparrow.mp4", local_path = LOCAL_FILE)
    snake_entry = client.postItem(dirpath = "/tutorial9", filename = "snake.mp4", local_path = LOCAL_FILE)
    spidy_entry = client.postItem(dirpath = "/tutorial9", filename = "spidy.mp4", local_path = LOCAL_FILE)
    test_entry = client.postItem(dirpath = "/tutorial9", filename = "test.mp4", local_path = LOCAL_FILE)
    
    # set some tags on these files
    eagle_meta_entry = client.createMeta(path = eagle_entry.path, tags = [Tag("movie"), Tag("bird"), Tag("birdwatching"),])
    sparrow_meta_entry = client.createMeta(path = sparrow_entry.path, tags = [Tag("bird"), Tag("documentary")])
    snake_meta_entry = client.createMeta(path = snake_entry.path, tags = [Tag("reptile"), Tag("documentary")])
    spidy_meta_entry = client.createMeta(path = spidy_entry.path, tags = [Tag("movie"), Tag("superhero"),])
    
    # get meta feed (= all files and sub-dirs of tutorial 9)
    feed = client.getMetaFeedFromPath(path = "/tutorial9")
    print "\n Getting all meta entries under path '/tutorial9'"
    for e in feed.entry:
        print "\nMeta Entry URI: " + str(e.id.text)
        print "name: " + str(e.content.params.name.text)
        print "size: " + str(e.content.params.size.text)
        print "updated: " + str(e.content.params.updated.text)
        print "mimetype: " + str(e.content.params.mimetype.text)
        for t in e.content.params.tag:
            print "tag: " + t.text
        for t in e.content.params.meta:
            print "Meta element" + " (vocab=" + t.vocab + "):"
            print "* name: " + t.name
            if t.text:
                print "* value: " + t.text

    # query meta resource based on tag (= all files under /tutorial9/ that have the tag 'documentary')
    qry = rawsc.Query()
    qry["tag"] = "documentary"
    qry["kind"] = "file"
    print "\n Getting all file entries under path '/tutorial9' that are tagged as 'documentary'"
    feed = client.getMetaFeedFromPath(path = "/tutorial9", query = qry)
    for e in feed.entry:
        print "\nMeta Entry URI: " + str(e.id.text)

    # query meta resource based on tags (= all files under /tutorial9/ that have the tag 'documentary' but not 'bird')
    qry = rawsc.Query()
    qry["tag"] = "documentary,-bird"
    qry["kind"] = "file"
    print "\n Getting all file entries under path '/tutorial9' that are tagged as 'documentary' but not 'bird'"
    feed = client.getMetaFeedFromPath(path = "/tutorial9", query = qry)
    for e in feed.entry:
        print "\nMeta Entry URI: " + str(e.id.text)

    # query meta resource based on tags (= all files under /tutorial9/ which have tags that contain both of these strings (case sensitive): 'doc' + 'bird')
    qry = rawsc.Query()
    qry["qtag"] = "+doc,+bird"
    qry["kind"] = "file"
    print "\n Getting all file entries under path '/tutorial9' which have tags that contain both of these strings (case sensitive): 'doc' + 'bird'"
    feed = client.getMetaFeedFromPath(path = "/tutorial9", query = qry)
    for e in feed.entry:
        print "\nMeta Entry URI: " + str(e.id.text)

    # query meta resource based on tags (= all files under /tutorial9/ which have tags that contain either of these strings (case insensitive): 'TILE' + 'Hero')
    qry = rawsc.Query()
    qry["iqtag"] = "TILE,Hero"
    qry["kind"] = "file"
    print "\n Getting all file entries under path '/tutorial9' which have tags that contain either of these strings (case insensitive): 'TILE' + 'Hero'"
    feed = client.getMetaFeedFromPath(path = "/tutorial9", query = qry)
    for e in feed.entry:
        print "\nMeta Entry URI: " + str(e.id.text)

    # # delete all manual metadata (= tags and meta elements) - doesn't delete the file (= item resource)
    # client.delete(eagle_meta_entry.id.text)
    # client.delete(sparrow_meta_entry.id.text)
    # client.delete(snake_meta_entry.id.text)
    # client.delete(spidy_meta_entry.id.text)
    # 
    # # delete files
    # client.delete(eagle_entry.id.text)
    # client.delete(sparrow_entry.id.text)
    # client.delete(snake_entry.id.text)
    # client.delete(spidy_entry.id.text)

except rawsc.service.Error, e:
    print "Error Response from server, contents = %s.\n" % str(e)
    error_dict = e[0] # error dict inside the first tuple elem
    print "status code : " + str(error_dict["status"]) + "\n"
    if error_dict.has_key("body"):
        print "error body : " + error_dict["body"] + "\n"
except rawsc.RawscException, e:
    print "RawscException caught, reason = %s.\n" % str(e)
except StandardError, e:
    print "StandardError caught, reason = %s.\n" % str(e)
except:
    print "unhandled exception caught\n"
